package org.javapict;

//import java.util.Enumeration;

//import java.util.Enumeration;
//import java.util.Hashtable;
//import java.util.Hashtable;

import java.util.Enumeration;

import org.deuce.*;
/* ready : a boolean to keep track whether the channel is ready for new data or not
 * 		 true -> channel is free to receive data
 * 		 false -> channel already contains some data
 * msgStore : a dictionary which will contain the actual data or message
 * */
//import java.util.Dictionary;
//import java.util.Enumeration;
//import java.util.Hashtable;
//import java.util.Map;

public class _Channel{
	private boolean ready = true;
	private _Message msgStore;
	public _Channel(){
		ready = true;
		msgStore = new _Message();
	}
	//@SuppressWarnings("rawtypes")
	@Atomic
	private void deepcopy(_Message d, _Message newd){
		if(d != null){
			Enumeration<?> e = d.dict.keys();
			//System.out.println("is dict empty = "+d.dict.isEmpty());
			//newd = new _Message(d);
			//newd.dict = new Hashtable<Comparable, Comparable>();
			while(e.hasMoreElements()){
				Comparable<?> key = (Comparable<?>) e.nextElement();
				//System.out.println("MSG KEY "+ key);
				Comparable<?> val = (Comparable<?>)d.dict.get(key);
				//System.out.println("MSG val "+ val);
				if(newd == null){
					System.out.println("cannot deepcopy");
				}
				else 
					newd.dict.put(key, val); 
			}
		}
		else{
			System.out.println("Dict is empty");
		}
		//System.out.println("leaving DEEPCOPY");
	}
	@Atomic
	public boolean Send(_Message msg){
		//System.out.println("in _Channel.Send "+ready);
		if(ready==false)
			return false;
		deepcopy(msg, this.msgStore);
		
		ready = false;
		return true;
	}
	@Atomic
	public boolean Receive(_Message msg){
		//System.out.println("in _Channel.Receive "+ready);
		if(ready) return false;
		deepcopy(msgStore, msg);
		ready = true;
		return true;
	}
}